package com.rizzo.android.content;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.rizzo.android.domain.ErrorData;
import com.rizzo.android.domain.Performance;
import com.rizzo.android.domain.PerformanceData;
import com.rizzo.android.domain.Quota;
import com.rizzo.android.domain.Trend;
import com.rizzo.android.domain.TrendData;

import java.sql.SQLException;

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

	public static final String DATABASE_NAME = "rizzo.db";
	private static final int DATABASE_VERSION = 1;
	private static DatabaseHelper instance;

	public static synchronized DatabaseHelper getInstance(Context c) {
		if (instance == null) {
			instance = new DatabaseHelper(c);
		}
		return instance;
	}

	private DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
		try {
			TableUtils.createTable(connectionSource, Error.class);
			TableUtils.createTable(connectionSource, ErrorData.class);
			TableUtils.createTable(connectionSource, Performance.class);
			TableUtils.createTable(connectionSource, PerformanceData.class);
			TableUtils.createTable(connectionSource, Quota.class);
			TableUtils.createTable(connectionSource, Trend.class);
			TableUtils.createTable(connectionSource, TrendData.class);
		} catch (SQLException e) {
			Log.e(this.getClass().getCanonicalName(), "Unable to create tables.", e);
			throw new RuntimeException(e);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {
		// TODO when upgrading the db...
	}

	public Dao<Error, Long> getErrorDao() throws SQLException {
		return getDao(Error.class);
	}

	public Dao<ErrorData, Long> getErrorDataDao() throws SQLException {
		return getDao(ErrorData.class);
	}

	public Dao<Performance, Long> getPerformanceDao() throws SQLException {
		return getDao(Performance.class);
	}

	public Dao<PerformanceData, Long> getPerformanceDataDao() throws SQLException {
		return getDao(PerformanceData.class);
	}

	public Dao<Quota, Long> getQuotaDao() throws SQLException {
		return getDao(Quota.class);
	}

	public Dao<Trend, Long> getTrendDao() throws SQLException {
		return getDao(Trend.class);
	}

	public Dao<TrendData, Long> getTrendDataDao() throws SQLException {
		return getDao(TrendData.class);
	}
}
